package com.neusoft.controller;

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;
import java.util.Properties;

import javax.mail.Authenticator;
import javax.mail.Message;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.Message.RecipientType;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.aspectj.apache.bcel.classfile.Code;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.fastjson.JSON;
import com.neusoft.bean.TabBbsTopicinfo;
import com.neusoft.bean.TabBbsUserinfo;
import com.neusoft.bean.UploadResJson;
import com.neusoft.service.IUserService;
import com.neusoft.util.MailStrUtil;
import com.neusoft.util.MailUtil;
import com.neusoft.util.UUIDUtils;


@Controller
@RequestMapping("/user")
public class UserController {
	
	@Autowired
	private IUserService iUserService;
	
	
	
	@RequestMapping("/login")
	public String login() {
		return "user/login";
	}
	/*
	@RequestMapping("/submit_login")
	public String submit_login(TabBbsUserinfo tabBbsUserinfo) {
		System.out.println(tabBbsUserinfo.getPassword());
		
		return "user/home";
		
	}
*/
	
	
	/**
	 * 登录后获取user存session
	 * 
	 * @ResponseBody
	 * 这个注解表示该方法的返回结果直接写入HTTP response body 中，一般在异步获取数据时使用
	 * 在使用@RequestMapping后，返回值通常解析为跳转路径，加上@ResponseBody后，返回结果直接
	 * 写入HTTP response body 中，不会被解析为跳转路径，比如异步请求，希望响应的结果是json
	 * 数据，那么加上@ResponseBody后，就会直接返回json数据
	 * 
	 * 
	 * @param request
	 * @param scode2
	 * @return
	 */
	@RequestMapping("/submit_login")
	@ResponseBody
	public String submit_login(HttpServletRequest request,String scode2,TabBbsUserinfo tabBbsUserinfo) {
		//从session中取
		HttpSession session = request.getSession();
		String scode1 = (String) session.getAttribute("scode");
		
//		System.out.println("系统验证码是："+scode1);
//		System.out.println("我输入的验证码是："+scode2);
//		System.out.println("下面进行比较~~~");
		if(scode1.equals(scode2)){
//			System.out.println("比较完毕，两个相同~~");
			TabBbsUserinfo tabBbsUserinfo1 = iUserService.getUser(tabBbsUserinfo);
			
			if (tabBbsUserinfo1 == null) {
				return "-1";
			}else {
				session.setAttribute("userinfo", tabBbsUserinfo1);
				return "1";
			}
			
		}else {
//			System.out.println("比较完毕，两个不相同~~");
			return "0";
		}
	}
	
	
	
	/**
	 * 跳转index个人页面
	 * @return
	 */
	@RequestMapping("/index")
	public String index() {
		return "user/index";
		
	}
	
	/**
	 * 跳转HOME个人页面
	 * @return
	 */
	@RequestMapping("/home")
	public String home() {
		return "user/home";
		
	}
	
	/**
	 * 跳转message个人页面
	 * @return
	 */
	@RequestMapping("/message")
	public String message() {
		return "user/message";
		
	}
	
	/**
	 * 跳转set个人页面
	 * @return
	 */
	@RequestMapping("/set")
	public String set() {
		return "user/set";
		
	}
	
	
	
	
	/**
	 * 退出
	 * @param request
	 * @return
	 */
	@RequestMapping("/logout")
	public String logout(HttpServletRequest request) {
		HttpSession session = request.getSession();
		session.invalidate();
		return "redirect:/";
	}
	
	
	@RequestMapping("/reg")
	public String reg() {
		return "user/reg";
	}
	
	
	
	
	
	/**
	 * 注册,发邮箱
	 * 参数用  用户
	 * @return
	 */
	@RequestMapping("/submit_reg")
	public ModelAndView submit_reg(TabBbsUserinfo tabBbsUserinfo) {
		//注册时邮箱发邮件，所以把邮箱的代码考过来
		String mail = tabBbsUserinfo.getEmail();
		String code = UUIDUtils.getUUID();
		//String code = "000000000000000000";
		
		//将原来的代码提取出来，放到MailUtil中，然后引用。
		MailUtil.sendMail(mail,code);
		tabBbsUserinfo.setCode(code);
		tabBbsUserinfo.setStatus(0);
		iUserService.addUser(tabBbsUserinfo);
		
		
		ModelAndView modelAndView = new ModelAndView();
		//下面是做数据共享 的，就像是往request中存东西的。
		modelAndView.addObject("mail", MailStrUtil.getMailStr(tabBbsUserinfo.getEmail()));
		modelAndView.addObject("nickname", tabBbsUserinfo.getNickname());
		modelAndView.setViewName("user/reg_success");
		return modelAndView;
	}
	
	
	
	/**
	 * 激活用户
	 * @return
	 */
	@RequestMapping("/user_active")
	public ModelAndView user_active(String code) {
		//返回的是user，所以用这个接
		TabBbsUserinfo tabBbsUserinfo = iUserService.get_User(code);
		ModelAndView modelAndView = new ModelAndView();
		
		if (tabBbsUserinfo == null) {
			modelAndView.addObject("msg", "对不起，激活失败，");
		}else {
			//先清空验证码
			tabBbsUserinfo.setCode(null);
			tabBbsUserinfo.setStatus(1);
			iUserService.active_user(tabBbsUserinfo);
			
			modelAndView.addObject("msg", "恭喜您，激活成功，");
		}
		//跳转页面
		modelAndView.setViewName("user/active_msg");
		return modelAndView;
	}
	
	
	/**
	 * 注册邮箱的ajax判定
	 */
	//用响应输出流给
	@RequestMapping("/check")
	public void check(TabBbsUserinfo tabBbsUserinfo,HttpServletResponse response) {
		TabBbsUserinfo tabBbsUserinfo2 =  iUserService.check(tabBbsUserinfo);
		System.out.println("hahahh hnajlknsdlkofnasio");
		try {
			PrintWriter out = response.getWriter();

			if (tabBbsUserinfo2 == null) {
				//1说明可以注册
				System.out.println("hahahh hnajlknsdlkofnasio");
				out.println(1);
			}else {
				
				out.println(0);
			}
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	}
	
	
	
	/**
	 * 上传头像
	 * file.getOriginalFilename()输出文件名在控制台，先看看能不能获取到
	 * @param file
	 */
	@RequestMapping("/upload")
	public void upload(@RequestParam MultipartFile file,HttpServletRequest request,HttpServletResponse response) {
		
		//最后写上面的这些，
		HttpSession session = request.getSession();
		TabBbsUserinfo userinfo = (TabBbsUserinfo) session.getAttribute("userinfo");
		
		
		
//		System.out.println(file.getOriginalFilename());
		//File.separator能表明当前系统的层级，可以自动识别当前系统是“/”  还是"\"
		String path = request.getServletContext().getRealPath("/res/img")+File.separator;
		File filePath = new File(path);
		if (!filePath.exists()) {
			filePath.mkdir();
		}
		//先生成旧的文件名，再新的，为了不重名，加时间戳
		String fileName = file.getOriginalFilename();
		//从“.”的位置开始截取，拼接
		String newFileName = new Date().getTime()+fileName.substring(fileName.indexOf("."));
		File file1 = new File(path,newFileName);
		try {
			//这样文件就过去了
			//不是存在tomcat上，而是存在我们建立的文件夹中
			file.transferTo(file1);
			
			
			//最后补充
			userinfo.setHeadUrl(request.getContextPath()+ "/res/img/" +newFileName);
			/*因为修改完头像后页面上面的小的头像显示不会变，要刷新一下，
			但是刷新后获取的是session中的，session里面的并没有改变，所以要更新session中的头像*/
			session.setAttribute("userinfo", userinfo);
			iUserService.update_head_url(userinfo);
			
			
			UploadResJson urj = new UploadResJson();
			urj.setStatus(0);
			urj.setSrc(request.getContextPath()+ "/res/img/" + newFileName);
			urj.setMsg("爱你呦~~~~");//随便写点，不写也行
			
			String jsonStr = JSON.toJSONString(urj);
			PrintWriter out = response.getWriter();
			out.println(jsonStr);
			
			
		} catch (IllegalStateException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		
	}
	
	
	
	
}
